package 基础.reflect反射_注解;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Val{
    int value() default 0;
}

class Point{
    private int x;

    @Val(value=200)
    private int y;

    private Point(){}
    private Point(int x,int y){
        this.x=x;
        this.y=y;
    }
    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

}

public class ReflectTests {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //1.获取字节码对象
        Class<Point> pointClass = Point.class;
        //2.获取构造方法对象
        Constructor<Point> declaredConstructor =
                pointClass.getDeclaredConstructor(int.class,int.class);
        declaredConstructor.setAccessible(true);
        //3.通过构造方法对象构建类的实例
        Point point = declaredConstructor.newInstance(10,20);
        System.out.println(point);
        //4.修改x属性的值
        Field x = pointClass.getDeclaredField("x");
        x.setAccessible(true);
        x.set(point,100);
        System.out.println(point);

        //5.修改y属性的值为@Val注解中value的值
        Field y=pointClass.getDeclaredField("y");
        y.setAccessible(true);
        Val declaredAnnotation = y.getDeclaredAnnotation(Val.class);
        y.set(point, declaredAnnotation.value());
        System.out.println(point);

    }
}
